import requests
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta

# 配置信息
API_KEY = "your_openweathermap_api_key"  # 去https://openweathermap.org注册获取
CITY = "Beijing"
LAT = 39.9042
LON = 116.4074
EMAIL_CONFIG = {
    "sender": "your_email@example.com",
    "password": "your_email_password",
    "smtp_server": "smtp.example.com",
    "smtp_port": 587
}


def get_weather_data():
    """获取天气数据"""
    url = f"https://api.openweathermap.org/data/3.0/onecall?lat={LAT}&lon={LON}&exclude=current,minutely,hourly&appid={API_KEY}&units=metric"

    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {str(e)}")
        return None


def analyze_weather(data):
    """分析天气数据"""
    if not data:
        return None

    alerts = data.get("alerts", [])
    daily_data = data["daily"][1]  # 获取第二天数据

    # 解析天气信息
    weather_info = {
        "date": datetime.fromtimestamp(daily_data["dt"]).strftime("%Y-%m-%d"),
        "temp_day": daily_data["temp"]["day"],
        "temp_night": daily_data["temp"]["night"],
        "weather": daily_data["weather"][0]["main"],
        "description": daily_data["weather"][0]["description"],
        "pop": daily_data["pop"] * 100,  # 降水概率转百分比
        "alerts": [alert["event"] for alert in alerts]
    }

    return weather_info


def send_alert(weather_info, recipient):
    """发送邮件提醒"""
    if not weather_info:
        return

    # 构建邮件内容
    subject = "天气预警提醒" if weather_info["alerts"] else "天气预报通知"

    body = f"""
    明日天气报告 ({weather_info["date"]})
    -------------------------------
    白天温度: {weather_info["temp_day"]}℃
    夜间温度: {weather_info["temp_night"]}℃
    天气状况: {weather_info["weather"]} ({weather_info["description"]})
    降水概率: {weather_info["pop"]}%
    """

    if weather_info["alerts"]:
        body += "\n预警信息:\n• " + "\n• ".join(weather_info["alerts"])

    # 判断是否需要发送提醒
    send_email = False
    if weather_info["pop"] > 60 or weather_info["alerts"]:
        send_email = True
        subject = "⚠️ 天气预警提醒" if weather_info["alerts"] else "🌧️ 降雨提醒"

    if send_email:
        msg = MIMEText(body, "plain", "utf-8")
        msg["Subject"] = subject
        msg["From"] = EMAIL_CONFIG["sender"]
        msg["To"] = recipient

        try:
            with smtplib.SMTP(EMAIL_CONFIG["smtp_server"], EMAIL_CONFIG["smtp_port"]) as server:
                server.starttls()
                server.login(EMAIL_CONFIG["sender"], EMAIL_CONFIG["password"])
                server.sendmail(EMAIL_CONFIG["sender"], recipient, msg.as_string())
            print("提醒邮件已发送")
        except Exception as e:
            print(f"邮件发送失败: {str(e)}")


if __name__ == "__main__":
    # 获取天气数据
    weather_data = get_weather_data()

    if weather_data:
        # 分析天气
        tomorrow_weather = analyze_weather(weather_data)

        # 发送提醒（替换为你的接收邮箱）
        send_alert(tomorrow_weather, "recipient@example.com")